#pragma once 

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

#define LINE_SIZE 1024
#define FLUSH_NOW 1
#define FLUSH_LINE 2
#define FLUSH_FULL 4

struct myFILE 
{
    unsigned int flags;
    int fileno;
    //缓冲区
    char cache[LINE_SIZE];
    int cap;
    int pos;//下次写入的位置
};


 myFILE* my_fopen(const char*path,const char* flag)
{
    int flag1 = 0;
    mode_t mode = 0666;
    int iscreate = 0;
    if(strcmp("r",flag) == 0)
    {
        flag1 = (O_RDONLY);
    }
    else if(strcmp("w",flag) == 0)
    {
        flag1 = (O_WRONLY | O_CREAT | O_TRUNC);
        iscreate = 1;
    }
    else if(strcmp("a",flag) == 0)
    {
        flag1 = (O_WRONLY | O_CREAT | O_APPEND);
        iscreate = 1;
    }
    else 
    {

    }
    int fd = 0;
    if(iscreate)
        fd = open(path,flag1,mode);
    else 
        fd = open(path,flag1);
    if(fd < 0)return NULL;
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(!fp) return NULL;
    fp->fileno = fd;
    fp->flags = FLUSH_LINE;

    fp->cap = LINE_SIZE;
    fp->pos = 0;

    return fp;  
}

void my_fflush(myFILE* fp)
{
    write(fp->fileno,fp->cache,fp->pos);
    fp->pos =0;
}

ssize_t my_fwrite(myFILE* fp,const char* data,int len)
{
    // 写入操作本质是拷贝，如果条件允许，就刷新，否则就不刷新
    memcpy(fp->cache+fp->pos,data,len);
    fp->pos+=len;

    if((fp->flags & FLUSH_LINE) && (fp->cache[fp->pos-1] == '\n'))
    {
        my_fflush(fp);
    }
    return len;

}

void my_fclose(myFILE* fp)
{
    my_fflush(fp);
    close(fp->fileno);
    delete fp;
}

   // myFILE* fp = my_fopen();
   // my_fclose();

